package com.cby.library.common.ext

import android.graphics.drawable.Drawable
import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cby.library.common.R

fun EditText.afterTextChange(afterTextChanged: (String) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            afterTextChanged.invoke(s.toString())
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }
    })
}

fun ImageView.load(url: String) {
    val options = RequestOptions().apply {
        centerCrop()
        placeholder(R.drawable.loading_empty)
    }
    Glide.with(context)
        .load(url)
        .apply(options)
        .into(this)
}

fun ImageView.load(url: String?, placeholder: Int) {
    val options = RequestOptions().apply {
        centerCrop()
        placeholder(placeholder)
    }
    Glide.with(context)
        .load(url)
        .apply(options)
        .into(this)
}

fun View.setBackgroundKeepingPadding(drawable: Drawable) {
    val padding = intArrayOf(
        paddingLeft, paddingTop, paddingRight,
        paddingBottom
    )
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        background = drawable
    } else {
        setBackgroundDrawable(drawable)
    }
    setPadding(padding[0], padding[1], padding[2], padding[3])
}

/**
 * 拓展函数：设置字体颜色
 * @receiver TextView
 * @param resId Int
 */
fun TextView.setFontColor(resId: Int) {
    this.setTextColor(ContextCompat.getColor(context, resId))
}

/**
 * 拓展函数：获取字符串
 * @receiver TextView
 * @param resId Int
 */
fun View.getString(resId: Int): String {
    return context.getString(resId)
}